import sys
import quopri
import gzip
import socket
import urllib.request, urllib.parse, urllib.error
import http.cookiejar
import json
from PIL import Image

class HttpTest:
  def __init__(self, timeout=10, addHeaders=True, addCookies=True):
    socket.setdefaulttimeout(timeout)
    self.__opener = urllib.request.build_opener()
    urllib.request.install_opener(self.__opener)
    if addHeaders:
      self.__addHeaders()
    if addCookies:
      self.__addCookiesjar()

  def __error(self, e):
    print(e)

  def __addHeaders(self):
    self.__opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko)\
      Chrome/34.0.1847.116'),
                                    ('Connection', 'keep-alive'),
                                    ('Cache-Control', 'no-cache'),
                                    ('Accept-Language', 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3'),
                                    ('Accept-Encoding', 'gzip, deflate'),
                                    ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')]

  def __decode(self, webpage, charset):
    if(webpage.startswith(b'\x1f\x8b')):
      return gzip.decompress(webpage).decode(charset, 'ignore')
    else:
      return webpage.decode(charset, 'ignore')

  def __addCookiesjar(self):
    cj = http.cookiejar.CookieJar()
    self.__opener.add_handler(urllib.request.HTTPCookieProcessor(cj))

  def addProxy(self, host, type='http'):
    proxy = urllib.request.ProxyHandler({type:host})
    self.__opener.add_handler(proxy)

  def addAuth(self, url, user, pwd):
    pwdMsg = urllib.request.HTTPPasswordMgrWithDefaultRealm()
    pwdMsg.add_password(None, url, user, pwd)
    auth = urllib.request.HTTPBasicAuthHandler(pwdMsg)
    self.__opener.add_handler(auth)

  def get(self, url, params={}, headers={}, charset='utf8'):
    if params:
      url += '?' + urllib.parse.urlencode(params)

    request = urllib.request.Request(url)
    for k, v in headers.items():
      request.add_header(k, v)

    try:
      response = urllib.request.urlopen(request)
    except urllib.error.HTTPError as e:
      self.__error(e)
    else:
      return self.__decode(response.read(), charset)

  def post(self, url, params={}, headers={}, charset='utf8'):
    params = urllib.parse.urlencode(params)
    request = urllib.request.Request(url, data=params.encode(charset))
    for k, v in headers.items():
      reqeust.add_header(k, v)

    try:
      response = urllib.request.urlopen(request)
    except urllib.error.HTTPError as e:
      self.__error(e)
    else:
      return self.__decode(response.read(), charset)

  def download(self, url, savefile):
    header_gzip = None
    for header in self.__opener.addheaders:
      if 'Accept-Encoding' in header:
        header_gzip = header
        self.__opener.addheaders.remove(header)

    __perlen = 0
    def reporthook(a, b, c):
      if c > 1000000:
        nonlocal __perlen
        per = (100.0 * a * b) / c
        if per > 100:
        	per = 100
        per = '{:.2f}%'.format(per)
        print('\b'*__perlen, per, end='')
        sys.stdout.flush()
        __perlen = len(per) + 1

    print('-->{}\t'.format(url), end='')

    try:
      urllib.request.urlretrieve(url, savefile, reporthook)
    except urllib.error.HTTPError as e:
      self.__error(e)
    finally:
      self.__opener.addheaders.append(header_gzip)
      print()

  def parse_json():
    result = get('https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=2014-05-17&leftTicketDTO.from_station=EGG&leftTicketDTO.to_station=SZQ&purpose_codes=ADULT')
    ticket_json = json.loads(result)
    for query in ticket_json['data']:
      print(query['queryLeftNewDTO']['start_time'])

if __name__ == '__main__':
  ht = HttpTest()
  # ht.download('http://www.baidu.com/', r'e:\baidu.html')
  # print(sys.argv)
  # if len(sys.argv) < 3:
  #   print('argv missing')
  #   sys.exit()

  # pass

